package com.qhgrain.app.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paas.base.modules.utils.lang.StringUtil;
import com.paas.base.modules.utils.page.PageBean;
import com.qhgrain.app.constant.RoleEnum;
import com.qhgrain.app.constant.UrlEnum;
import com.qhgrain.app.util.ConfigUtil;
import com.qhgrain.app.vo.PairVo;
import com.qhgrain.app.vo.RoleVo;
import com.qhgrain.gway.util.HttpUtil;
import com.sun.star.uno.RuntimeException;

@Service
public class RoleService {

	private static Logger LOG = LoggerFactory.getLogger(RoleService.class);

	private final static String BASE_URL = ConfigUtil.getProperties(UrlEnum.MENU_ROLE_PERMISSION)+"/role";

	public RoleVo find(String roleId) throws IOException{
		String vo = HttpUtil.get(BASE_URL+"/get/role/"+roleId);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			return JSONObject.parseObject(voJson.getString("data"), RoleVo.class);
		}else{
			throw new RuntimeException( "从api获取对象信息失败...vo="+vo);
		}
	}
	
	public RoleVo findByRoleCode(String roleCode)throws Exception{
		String vo = HttpUtil.get(BASE_URL+"/getByRoleCode/"+roleCode);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			return JSONObject.parseObject(voJson.getString("data"), RoleVo.class);
		}else{
			throw new RuntimeException( "从api根据roleCode获取对象信息失败...vo="+vo);
		}
	}
	public List<String> getPermissionsBy(String roleId,String appId) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("roleId", roleId);
		if(StringUtil.isNotBlank(appId)){
			map.put("appId", appId);
		}
		String vo = HttpUtil.postFormParams(BASE_URL, "/get/permission", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			return JSONArray.parseArray(voJson.getString("data"), String.class);
		}else{
			LOG.error("根据roleId,appId从api获取数据失败...roleId="+roleId+",appId="+appId+"...."+vo);
			throw new RuntimeException("根据roleId,appId从api获取数据失败");
		}
		
	}
	/**
	 * 获取所有角色
	 * 如果参数userId为null ,则返回所有角色
	 * 如果参数userId不为null,则返回用户所拥有的角色
	 * @param userId
	 * @return
	 * @throws Exception 
	 */
	public JSONArray getAll(String userId) throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		if(StringUtil.isNotBlank(userId)){
			map.put("userId", userId);
		}
		try {
			String vo = HttpUtil.get(BASE_URL+"/get/all", map);
			JSONObject voJson = JSONObject.parseObject(vo);
			if("1".equals(voJson.getString("state"))){
				
				JSONArray array = voJson.getJSONArray("data");
				
				return array;
			}else{
				throw new RuntimeException("api获取所有应用list,api出错...."+vo);
			}
		} catch (Exception e) {
			throw e;
		}
	}
	
	public void saveRolePermission(String roleId,List<String> permissionIds) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("roleId", roleId);
		String s = StringUtils.join(permissionIds,",");
		map.put("permissionIds", s);
		
		String vo = HttpUtil.postFormParams(BASE_URL, "/grant/permissions", map);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			
		}else{
			LOG.error("保存角色权限关联出错,api出错..."+vo);
			throw new RuntimeException("保存角色权限关联出错,api出错..."+vo);
		}
	}
	
	/**
	 * 
	 * 2016年4月6日 上午11:56:14  
	 * @tags 获取所有角色分页
	 * @author zhaoyq
	 */
	public PageBean<Object> queryRoles(String pageNo,String pageSize,String roleName,String roleType) throws Exception{
		if(StringUtils.isEmpty(pageNo)){
			pageNo="1";
		}
		if(StringUtil.isBlank(pageSize)){
			pageSize = "10";
		}
		Map<String,Object> map = new HashMap<String,Object>();
		if(StringUtil.isNotBlank(roleName)){
			map.put("roleName", roleName.trim());
		}
		if(StringUtil.isNotBlank(roleType)){
			map.put("roleType", roleType.trim());
		}
		map.put("page", pageNo);
		map.put("pageSize", pageSize);
		
		String requestVo;
		PageBean<Object> pageBean = new PageBean<Object>(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
		try {
			requestVo = HttpUtil.postFormParams(BASE_URL, "/query/page", map);
			JSONObject voJson = JSONObject.parseObject(requestVo);
			if("1".equals(voJson.getString("state"))){
				JSONObject dataJson = voJson.getJSONObject("data");
				int count = dataJson.getIntValue("totalCount");
				JSONArray list = dataJson.getJSONArray("list");
				pageBean.setData(list);
				pageBean.setTotalCount(count);
			}else{
				LOG.error("角色查询,api出错。。。。",voJson.getString("exceptionMsg"));
			}
		
		} catch (IOException e) {
			LOG.error("角色查询出错。。。。",e);
			throw new RuntimeException();
		}
		return pageBean;

	}
	
	/**
	 *  获取用户拥有的角色
	 * 2016年4月6日 下午12:41:59  
	 * @tags 
	 * @author zhaoyq
	 * @return 用户拥有的角色列表 json数组，详细字段可看RoleVo
	 */

	public JSONArray getUserRoses(String userId) {
		String requestVo;
		JSONArray list = new JSONArray();
		Map<String,String> map = new HashMap<String,String>();
		if(StringUtil.isNotBlank(userId)){
			map.put("userId", userId.trim());
		}
		try {
//			requestVo = HttpUtil.postFormParams(BASE_URL, "/get/all", map);
			requestVo = HttpUtil.get(BASE_URL+"/get/all", map);
			JSONObject voJson = JSONObject.parseObject(requestVo);
			if("1".equals(voJson.getString("state"))){
				JSONArray dataJson = voJson.getJSONArray("data");
				if(dataJson!=null){
					list = dataJson;
				}
			}else{
				LOG.error("角色查询,api出错。。。。",voJson.getString("exceptionMsg"));
			}
		
		} catch (Exception e) {
			LOG.error("角色查询出错。。。。",e);
			throw new RuntimeException();
		}
		return list;
	}
	
	/**
	 * 更新用户拥有的角色
	 * 先删除原来拥有的角色，再批量添加新的角色列表
	 */
	public boolean saveUserRoses(String userId,String roleIds) {
		if(StringUtil.isBlank(userId)){
			return false;
		}
		boolean result = false;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		String requestVo;
		try {
			// 先删除原来拥有的角色
			requestVo = HttpUtil.postFormParams(BASE_URL, "/delete/userRole", map);
			JSONObject voJson = JSONObject.parseObject(requestVo);
			//成功后，添加新的角色
			if("1".equals(voJson.getString("state"))){
				if(StringUtil.isNotBlank(roleIds)){
					map.put("roleId", roleIds);
					map.put("userIds", userId);
					requestVo = HttpUtil.postFormParams(BASE_URL, "/grant/users", map);
					voJson = JSONObject.parseObject(requestVo);
					if("1".equals(voJson.getString("state"))){
						 result = true;
					}else{
						LOG.error("新增用户-角色关联关系，api出错...."+requestVo);
					}
				}else{
					result = true;
				}
				
			}else{
				LOG.error("删除用户角色,api出错。。。。"+requestVo);
			}
		
		} catch (IOException e) {
			LOG.error("用户角色操作出错。。。。",e);
			throw new RuntimeException(e.getMessage());
		}
		return result;
	}
	/**
	 * 角色-用户（1对多，关联）
	 * @param roleId
	 * @param userIds
	 * @return
	 */
	public boolean saveRoleUsers(String roleId,List<String> userIds){
		if(StringUtil.isBlank(roleId)){
			return false;
		}
		boolean result = false;
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("roleId", roleId);
		String requestVo;
		try {
			// 先删除角色原来的所有用户
			requestVo = HttpUtil.postFormParams(BASE_URL, "/delete/userRole", map);
			JSONObject voJson = JSONObject.parseObject(requestVo);
			//成功后，添加新的角色
			if("1".equals(voJson.getString("state"))){
				if(userIds != null && userIds.size() > 0){
					map.put("roleId", roleId);
					map.put("userIds", StringUtils.join(userIds,","));
					requestVo = HttpUtil.postFormParams(BASE_URL, "/grant/users", map);
					voJson = JSONObject.parseObject(requestVo);
					if("1".equals(voJson.getString("state"))){
						 result = true;
					}else{
						LOG.error("新增角色-用户关联，api出错..."+requestVo);
					}
				}
				
			}else{
				LOG.error("根据角色删除角色-用户关联,api出错。。。。"+voJson);
			}
		
		} catch (IOException e) {
			LOG.error("角色赋给用户操作出错。。。。",e);
			throw new RuntimeException(e.getMessage());
		}
		return result;
	}
	/**
	 * 角色-权限的关联
	 * @param roleId 角色id
	 * @param addPermissionIds 要新增的角色-权限关联
	 * @param deletePermissionIds 要删除的角色-权限关联
	 * @return
	 */
	public boolean grantRolePermission(String roleId,List<String> addPermissionIds,List<String> deletePermissionIds){
		boolean result = false;
		try {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("roleId", roleId);
			if(addPermissionIds != null && addPermissionIds.size() > 0){
				map.put("addPermissionIds", StringUtils.join(addPermissionIds,","));
			}
			if(deletePermissionIds != null && deletePermissionIds.size() > 0){
				map.put("deletePermissionIds", StringUtils.join(deletePermissionIds,","));
			}
			String vo = HttpUtil.postFormParams(BASE_URL, "/grant/permissions", map);
			JSONObject voJson = JSONObject.parseObject(vo);
			if("1".equals(voJson.getString("state"))){
				result = true;
			}else{
				
				LOG.error("角色授权，角色-权限关联，api失败"+vo);
			}
		} catch (Exception e) {
			LOG.error("角色授权，角色-权限关联，出错...",e);
		}
		
		return result;
	}
	
	public List<PairVo> getRoleAllType(){
		List<PairVo> list = new ArrayList<PairVo>();
		list.add(new PairVo(RoleEnum.APP_ROLE.getCode(),RoleEnum.APP_ROLE.getName()));
		list.add(new PairVo(RoleEnum.BUSINESS_ROLE.getCode(),RoleEnum.BUSINESS_ROLE.getName()));
		
		return list;
	}
	/**
	 * 根据应用id获取应用有哪些角色
	 * @param appId
	 * @return
	 * @throws IOException 
	 */
	public List<RoleVo> getRolesByApp(String appId) throws IOException{
		String vo = HttpUtil.get(BASE_URL+"/getRolesByAppId/"+appId);
		JSONObject voJson = JSONObject.parseObject(vo);
		if("1".equals(voJson.getString("state"))){
			return JSONArray.parseArray(voJson.getString("data"), RoleVo.class);
		}else{
			LOG.error("根据应用id获取角色，api失败....vo="+vo);
			throw new RuntimeException("根据应用id获取角色，api失败....vo="+vo);
		}
	}
}
